import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {AuthService} from "@core/service/AuthService";
import {UserInfo} from "@shared/models/UserInfo";
import {Router} from "@angular/router";
import {EmailValidator, FormBuilder, FormControl, FormGroup, Validators} from "@angular/forms";
import {NzSafeAny} from "ng-zorro-antd/core/types";
import {NzUploadFile} from "ng-zorro-antd/upload";
import {Observable, Observer} from "rxjs";
import {NzMessageService} from "ng-zorro-antd/message";
import {BBYUtils} from "@shared/utils/BBYUtils";
import {HttpHeaders} from "@angular/common/http";
import {api} from "@core/service/config/api";

class EmailEditParam{
  count=0
  captchaLoading=false
  subLoading=false
  email=''
  mailToken= ''
  edit= false
  error= ''
  captcha= ''
}
@Component({
  selector: 'bby-userinfo',
  templateUrl: './userinfo.component.html',
  styleUrls: ['./userinfo.component.scss']
})
export class UserinfoComponent implements OnInit {

  editStr='一只本小蛋';
  username = {
    edit: false,
    value:'',
    ok:false,
    error:''
  }
  email = new EmailEditParam()
  passwdFrom:FormGroup
  passwd={
    status:'pool', progress: 0,
    edit: false
  }
  passwordProgressMap: { [key: string]: 'success' | 'normal' | 'exception' } = {
    ok: 'success',
    pass: 'normal',
    pool: 'exception'
  };
  custom = {
    birthday:'',
    sex:'保密'
  }
  // 头像
  uploading=false;
  private interval: any;
  constructor(
    public authService:AuthService,
    private router:Router,
    private cdr: ChangeDetectorRef,
    private message: NzMessageService,
    fb: FormBuilder
  ) {
    this.authService.flashUserInfo()
    this.authService.getUserInfo()
    if (authService.userInfo?.sex){
      this.custom.sex=authService.userInfo?.sex
    }
    if (authService.userInfo?.birthday){
      let i = authService.userInfo.birthday.indexOf("T")
      if (i>0){
        this.custom.birthday=authService.userInfo.birthday.substring(0,i)
      }else this.custom.birthday=authService.userInfo.birthday
    }
    this.flashAvatar()
    let self = this;
    console.log(BBYUtils.createHeadersOption().headers)
    this.passwdFrom=fb.group(
      {
        password: [null, [Validators.required, Validators.minLength(6)
          , (control: FormControl)=>{
            if (control.value && control.value.length > 9) {
              self.passwd.status = 'ok';
            } else if (control.value && control.value.length > 5) {
              self.passwd.status = 'pass';
            } else {
              self.passwd.status = 'pool';
            }
            let len = control.value?.length||0;
            self.passwd.progress = len * 10 > 100 ? 100 : len * 10;
          }
        ]],
        confirm: [null, [Validators.required,(control: FormControl) => (control.value != self.passwdFrom?.controls.password.value)? { msg: '两次输入的密码不一致！'} : null]],
        currentPassword: [null, [Validators.required, Validators.minLength(6)]],
      },
      {
        // validators: MatchControl('password', 'confirm')
      })
  }
  flashAvatar(){
    this.authService.avatarUrl=`${api.getAvatar}/${this.authService.userInfo?.userId}?tm=${new Date().getTime()}`;
  }
   checkPassword(control: FormControl): NzSafeAny {
    if (!control) {
      return null;
    }
    // eslint-disable-next-line @typescript-eslint/no-this-alias
    if (control.value && control.value.length > 9) {
      this.passwd.status = 'ok';
    } else if (control.value && control.value.length > 5) {
      this.passwd.status = 'pass';
    } else {
      this.passwd.status = 'pool';
    }
    //
    // if (this.passwd.visible) {
    //   self.progress = control.value.length * 10 > 100 ? 100 : control.value.length * 10;
    // }
  }
  ngOnInit(): void {
  }

  test() {

    this.router.navigate(["file/video" ],{ queryParams: { fileId: 'file.id',directId:'res.data.id' } });
  }

  getEmailCaptcha() {
    if (!this.authService.userInfo){
      return;
    }
    this.email.captchaLoading=true;
    BBYUtils.handelResult(
      this.authService.mailCaptcha(this.authService.userInfo.email),
      res => {
        this.email.captchaLoading=false;
        // this.email.mailToken=res.data;
        this.captchaCountRun();
      },
        res => {
          this.email.captchaLoading=false;
          this.message.error(res.msg)
        })

  }

  oldMailConfirm() {
    if (!this.authService.userInfo){
      return;
    }
    this.email.subLoading=true;
    BBYUtils.handelResult(
      this.authService.getMailToken(this.authService.userInfo.email, this.email.captcha),
    res => {
      console.log(res)
      this.email.subLoading=false;
      this.email.mailToken=res.data;
      this.email.error='';
      this.email.captcha=''
      this.email.count=0;
      clearInterval(this.interval)
    },
      res => {
        this.email.subLoading=false;
        this.email.error=res.msg;
        this.message.error(res.msg)
      });

  }

  getNewEmailCaptcha() {
    if (!this.authService.userInfo){
      return;
    }
    if (this.email.email==''||this.email.email.indexOf('@')==-1){
      this.email.error='邮箱格式有误！'
    }
    if (this.email.email==this.authService.userInfo.email){
      this.email.error='邮箱没有变化！'
    }
    this.email.error=''
    this.email.captchaLoading=true;
    BBYUtils.handelResult(
      this.authService.mailCaptcha(this.email.email),
      res => {
        console.log(res)
        this.email.captchaLoading=false;
        this.email.error='';
        this.captchaCountRun();
      },
      res => {
        this.email.subLoading=false;
        this.email.error=res.msg;
        this.message.error(res.msg)
      });

  }

  newMailConfirm() {
    let data={
      newMail:this.email.email,
      mailToken:this.email.mailToken,
      captcha: this.email.captcha
    }
    BBYUtils.handelResult(
      this.authService.mailEdit(data),
      res => {
        console.log(res)
        clearInterval(this.interval)
        this.message.success('修改成功')
        this.email = new EmailEditParam()
        this.authService.flashUserInfo()
      },
      res => {
        this.email.subLoading=false;
        this.email.error=res.msg;
        this.message.error(res.msg)
      });

  }
  passwdSubmit() {
    if (this.passwdFrom.invalid) {
      Object.keys(this.passwdFrom.controls).forEach(key => {
        this.passwdFrom.controls[key].markAsDirty();
        this.passwdFrom.controls[key].updateValueAndValidity();
      });
      return;
    }
    let data = {
      currentPw:this.passwdFrom.controls.currentPassword.value,
      newPw:this.passwdFrom.controls.password.value
    }
    BBYUtils.handelResult(
      this.authService.passwdEdit(data),
      res => {
        this.message.success("成功！")
        this.passwd.edit=false;
      },
      res => {
        this.message.error(res.msg)
      }
    )
    console.log(data)
  }
  checkUsername(){
    if (this.username.value==''){
      this.username.error='用户名为空！'
      this.username.ok=false;
      return
    }
    BBYUtils.handelResult(
      this.authService.checkUsername(this.username.value),
      res => {
        this.username.error=''
        this.username.ok=true;
      },
      res => {
        this.username.error=res.msg
        this.username.ok=false;
      }
    )
  }
  usernameConfirm() {
    if (this.username.value==''||!this.username.ok){
      return;
    }
    BBYUtils.handelResult(
      this.authService.usernameEdit(this.username.value),
      res => {
        this.message.success('修改成功！')
        this.authService.flashUserInfo();
      },
      res => {
        this.message.error(res.msg)
      }
    )
  }
  beforeUpload = (file: NzUploadFile, _fileList: NzUploadFile[]): Observable<boolean> =>{
    this.uploading = true
    return new Observable((observer: Observer<boolean>) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        this.message.error('只能上传 jpg/png文件 !');
        observer.complete();
        return;
      }
      const isLt2M = file.size! / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.message.error('图片必须小于 2MB!');
        observer.complete();
        return;
      }
      observer.next(isJpgOrPng && isLt2M);
      observer.complete();
    });
  }
  birthday=null;
  getHeaders(){
    let token = localStorage.getItem('token')
    return token ? {"token": token}:{}
  };

  private getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }

  handleChange(info: { file: NzUploadFile }): void {
    switch (info.file.status) {
      case 'uploading':
        // this.uploading = true;
        break;
      case 'done':
        // Get this url from response in real world.
        // this.getBase64(info.file!.originFileObj!, (img: string) => {
        //   this.uploading = false;
        //   this.avatarUrl = img;
        // });
        this.uploading = false;
        this.flashAvatar();
        break;
      case 'error':
        this.message.error('上传失败！');
        this.uploading = false;
        break;
    }
  }

  private captchaCountRun() {
    this.email.count=60;
    clearInterval(this.interval);
    this.interval = setInterval(() => {
      this.email.count--;
      this.cdr.detectChanges();
      if (this.email.count <= 0) {
        clearInterval(this.interval);
      }
    }, 1000);
  }

  sexChangeClick() {
    console.log(this.custom)
    this.authService.uploadCustom('sex',this.custom.sex=='保密'? '':this.custom.sex)
  }
  birthdayChangeClick() {
    console.log(this.custom.birthday)
    if (this.custom.birthday!=this.authService.userInfo?.birthday)
      this.authService.uploadCustom('birthday',this.custom.birthday)
  }
}
